import { menu } from '../../../app/decorator';

const { ccclass, property } = cc._decorator;

@ccclass
@menu(__filename)
export default class StringFormat extends cc.Component {
    @property
    private _args = '';
    @property({ type: cc.String, tooltip: '格式：数组JSON.stringify后的字符串' })
    get args() { return this._args; }
    set args(str) { this._args = str; this.updateRender(); }

    @property
    private _format = '';
    @property({ type: cc.String, tooltip: '%s作为占位符' })
    get format() { return this._format; }
    set format(str) { this._format = str; this.updateRender(); }

    private parse(param) {
        if (CC_DEBUG) {
            try {
                return JSON.parse(param);
            } catch (e) {
                cc.error('args参数错误');
                return null;
            }
        } else {
            return JSON.parse(param);
        }
        return null;
    }

    private updateRender() {
        const label = this.node.getComponent(cc.Label) || this.node.getComponent(cc.RichText);
        const array = this.parse(this.args);
        if (array) {
            const string = this.format.replace(/%s/g, () => array.length ? array.shift() : undefined);
            label.string = string;
        } else {
            label.string = 'args参数错误';
        }
    }
}